package com.mt.fpb.controller;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.mt.fpb.common.util.DateUtil;
import com.mt.fpb.common.util.GetCameraPreviewURL;
import com.mt.fpb.mapper.*;
import com.mt.fpb.model.*;
import com.mt.fpb.model.dto.BaseQueryParams;
import com.mt.fpb.model.vo.CommonResult;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

import static com.mt.fpb.common.util.DateUtil.getPastDate;

/**
 * 对接第三方数据控制层
 */
@RestController
@RequestMapping("/data")
public class DataController {
    @Resource
    private TVehicleOutMapper tVehicleOutMapper;

    @Resource
    private TWarningMapper tWarningMapper;

    @Autowired
    private TVehicleOutImageMapper tVehicleOutImageMapper;

    @Autowired
    private TVehicleOutVideoMapper tVehicleOutVideoMapper;

    @Autowired
    private CameraMapper cameraMapper;


    /**
     * 过磅称重检测采集数据接收
     * author:hjm
     *
     * @param map
     * @return
     */
    @PostMapping("/source/getVehicleInfo")
    public CommonResult getVehicleInfo(@RequestBody Map map) {
        // 注：后期接口需要添加认证信息  authorizeId字段来验证

        String vehicleInfoStr = (String) map.get("strData"); // 获取车辆的基本信息

        // base64解码
        String decodeStr = Base64.decodeStr(vehicleInfoStr);

        // 将json字符串转成json对象
        JSONObject jsonObject = JSON.parseObject(decodeStr);


        TVehicleOut vehicleOut = JSON.toJavaObject(jsonObject, TVehicleOut.class);

        if(!StringUtils.isEmpty(vehicleOut.getIsOverWeight())) { // 不为空
            if (vehicleOut.getIsOverWeight().equals(1)) { // 超过限度  新增到t_warning表中
                TWarning tWarning = new TWarning();
                tWarning.setInsertTime(new Date()); // 添加时间
                tWarning.setWarningType(3); // 超载
                tWarning.setMineCode(vehicleOut.getCheckId()); // 矿区编码
                tWarning.setWarningTime(vehicleOut.getCheckTime()); // 告警时间
                tWarning.setWarningStatus(0); // 未处理
                tWarning.setWarningSourceCode(vehicleOut.getDataId()); // 新增告警code

                tWarningMapper.insert(tWarning);
            }
        }
        // 新增基本数据到车辆信息表中===>基本信息表
        vehicleOut.setInsertTime(new Date());
        tVehicleOutMapper.insert(vehicleOut);

        String vehicleOutId =null;
        String imageArray = null;
        // 获取到数据id
        if(!StringUtils.isEmpty(vehicleOut.getDataId())){
             vehicleOutId = vehicleOut.getDataId();
        }
        // 新增到图片表中
        if(!StringUtils.isEmpty(vehicleOut.getImageArray())){
             imageArray = vehicleOut.getImageArray();
        }

        // 将字符串转成list
//        JSONArray imageArr = JSON.parseArray(imageArray);
        if(!StringUtils.isEmpty(imageArray)){
            List<TVehicleOutImage> imageList = JSONObject.parseArray(imageArray, TVehicleOutImage.class);

            for (int i = 0; i < imageList.size(); i++) {
                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                System.out.println(uuid);
                imageList.get(i).setVehicleOutImageId(uuid);
                imageList.get(i).setDataId(vehicleOutId);
                imageList.get(i).setInsertTime(new Date());
            }

            // 将list新增到数据库
            tVehicleOutImageMapper.insertList(imageList);
        }




        // 新增到视频表中
        if(!StringUtils.isEmpty(vehicleOut.getVideoArray())){
            String videoArray = vehicleOut.getVideoArray();
            // 将字符串转成list
//        JSONArray videoArr = JSON.parseArray(videoArray);
            List<TVehicleOutVideo> videoList = JSONObject.parseArray(videoArray, TVehicleOutVideo.class);

            for (int i = 0; i < videoList.size(); i++) {
                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                System.out.println(uuid);
                videoList.get(i).setVehicleOutVideoId(uuid);
                videoList.get(i).setDataId(vehicleOutId);
                videoList.get(i).setInsertTime(new Date());
            }

            // 将list新增到视频数据表中
            tVehicleOutVideoMapper.insertList(videoList);
        }



        return CommonResult.success(1);
    }


    /**
     *  分页获取监控点信息(主要是获取设备编码)
     *  author: hjm
     * @param map
     * @return
     */
    @PostMapping("/getVideoCode")
    public CommonResult getVideoCode(@RequestBody Map map) {

        JSONObject json = new JSONObject();
        json.put("pageNo",1);
        json.put("pageSize",1000);
        String data = GetCameraPreviewURL.GetCameraPreviewURL("/api/resource/v1/cameras", json);


        Example example = new Example(Camera.class);

        // 创建一个存储的list
        List<Camera> cameraList = new ArrayList<>();

        Map mapObj = (Map)JSON.parseObject(data);
        List list = (List)((Map)mapObj.get("data")).get("list");
        // 遍历list
        for (int i = 0; i < list.size(); i++) {
            Camera camera = new Camera();
            String cameraIndexCode = (String) ((Map)list.get(i)).get("cameraIndexCode");
            String cameraName = (String) ((Map)list.get(i)).get("cameraName");
            String regionIndexCode = (String) ((Map)list.get(i)).get("regionIndexCode");// 所属区域的唯一标识
            example.createCriteria().andEqualTo("cameraCode",cameraIndexCode);
            // 查询camper表中的code，相同则不添加，不同添加

            List<Camera> cameras = cameraMapper.selectByExample(example);

            if(cameras.size() < 1){ // 表中没有
                camera.setCameraCode(cameraIndexCode);
                camera.setCameraName(cameraName);
                camera.setMineCode(regionIndexCode); // 所属区域唯一标识
                // 新增 到 cameraList 中
                cameraList.add(camera);
            }

        }
        // 新增cameraList到camera表中
        cameraMapper.insertList(cameraList);

        return CommonResult.success(1);
    }







    /**
     *  获取视频直播地址   接口 待调整  !!!! 需要接收的参数   ：矿区编码和矿区的区域(例如开发区)
     *  author: hjm
     * @return
     */
    @GetMapping("/getVideoUrl")
    public CommonResult getVideoUrl(Camera camera) {


        String protocol = "ws";
        JSONObject json = new JSONObject();

        // 查询camera表
        List<Camera> cameraList = cameraMapper.selectAll();
        String data = "";
        // 数据list
        List<Map> mapList = new ArrayList<>();
        if(cameraList.size() > 0) {
            for (int i = 0; i < cameraList.size(); i++) {
                if (!StringUtils.isEmpty(cameraList.get(i).getCameraCode())) {
                    json.put("cameraIndexCode", cameraList.get(i).getCameraCode());
                    json.put("protocol", protocol);     // 还需要修改，这边的设备编码是list结构，需要循环来获取url地址
                    data = GetCameraPreviewURL.GetCameraPreviewURL("/api/video/v2/cameras/previewURLs", json);
                }
                // 解析data
                Map jsonObject = (Map) JSON.parseObject(data);

                if (!StringUtils.isEmpty(jsonObject.get("data"))) {

                    Map dataMap = (Map) jsonObject.get("data");// data:{"url":"url地址"}

                    if (!StringUtils.isEmpty(cameraList.get(i).getCameraName())) { // 矿区名称
                        dataMap.put("cameraName", cameraList.get(i).getCameraName());
                    }
                    if (!StringUtils.isEmpty(cameraList.get(i).getMineCode())) { // 矿区编码
                        dataMap.put("mineCode", cameraList.get(i).getMineCode());
                    }
                    if (!StringUtils.isEmpty(cameraList.get(i)) || !StringUtils.isEmpty(cameraList.get(i).getCameraCode())) {
                        String cameraCode = cameraList.get(i).getCameraCode();
                        System.out.println(cameraCode);
                        dataMap.put("cameraIndexCode", cameraCode);
                    }

                    mapList.add(dataMap);
                }
            }
        }



        return CommonResult.success(mapList);
    }



    /**
     *  获取回看视频地址    !!!!  请求参数：设备编码
     *  author: hjm
     * @param map
     * @return
     */
    @PostMapping("/getHistoryVideoUrl")
    public CommonResult getHistoryVideoUrl(@RequestBody Map map) {

        // 回看的时间段
//        Date beginTime = DateUtil.convert2Date((String) map.get("beginTime"), "yyyy-MM-dd'T'HH:mm:ss");
//        Date endTime = DateUtil.convert2Date((String) map.get("endTime"), "yyyy-MM-dd'T'HH:mm:ss");
        String beginTime = DateUtil.getISO8601(((String)map.get("beginTime")));
        String endTime = DateUtil.getISO8601(((String)map.get("endTime")));
        JSONObject json = new JSONObject();
        json.put("cameraIndexCode",map.get("cameraIndexCode")); // 设备编码
        json.put("beginTime",beginTime);
        json.put("endTime",endTime);
        String data = GetCameraPreviewURL.GetCameraPreviewURL("/api/video/v2/cameras/playbackURLs", json);
        // 解析data

        Map jsonMap =  (Map)JSON.parseObject(data);
        String url =  (String)((Map)jsonMap.get("data")).get("url"); // 视频回放url

        return CommonResult.success(url);
    }


    /**
     * 订阅接口
     * author:hjm
     * @param args
     */
    public static void main(String[] args) {  // 订阅接口
          JSONObject json = new JSONObject();
          long arr[] = new long[]{376833L,1417219L,131585L}; // 事件编码
          json.put("eventTypes", arr);
          json.put("eventDest", "http://3m160739y3.wicp.vip/data/recvHkWarningData"); // 接收数据推送的接口
          String data1 = GetCameraPreviewURL.GetCameraPreviewURL("/api/eventService/v1/eventSubscriptionByEventTypes", json);
          System.err.println(data1);
      }


    /**
     * 接收数据推送的接口
     * author:hjm
     * @param map
     */
    @PostMapping("recvHkWarningData")
    public  void getHkData(@RequestBody Map map) {
        System.out.println(map);

    }

}
